<template>

  <div :style="{height:height+30+'px',width:width}">
    <el-button v-if="!loading" type="success" icon="el-icon-download" size="mini"
      @click="getChartImage">导出报告</el-button>
    <div class="chart" ref="linechart" :style="{height:height+'px',width:width}"></div>
  </div>
</template>

<script>
  import * as echarts from 'echarts';
  require('echarts/theme/macarons'); // echarts theme
  import resize from './mixins/resize';

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: Number,
        default: window.innerHeight - 100,
      },
      text: {
        type: String,
        default: ''
      },
      unit: {
        type: Number,
        default: 1024,
      },
      subtext: {
        type: String,
        default: ''
      },
      chartData: {
        type: Object,
        required: true
      }
    },
    watch: {
      chartData: {
        deep: true,
        handler(val, oldValue) {
          // 使用节流技术来控制更新频率
          this.throttleSetOptions(val);
        }
      },
      subtext: {
        deep: true,
        handler(val) {
          this.subtext = val;
        }
      },
      unit: {
        deep: true,
        handler(val) {
          this.unitShow = val
        }
      },
      text: {
        deep: true,
        handler(val) {
          this.text = val;
        }
      }
    },
    data() {
      return {
        loading: false,
        chart: null,
        dataURL: '',
        unitShow: this.unit,
        mapping: {
          'INTERNET': 'internet文件',
          'OFFICE': 'office文件',
          'PROCEDURE': '程序文件',
          'TEMPORARYANDBACKUP': '临时和备份文件',
          'CONTAINER': '容器文件',
          'DEV': '软件开发文件',
          'VIDEO': '视频文件',
          'DATABASE': '数据库文件',
          'TEXT': '文本文件',
          'IMAGE': '文件时长',
          'SYSTEM': '系统文件',
          'CONFIG': '配置文件',
          'AUDIO': '音频文件',
          'EMAIL': '邮件文件',
          'MISCELLANEOUS': '杂项文件'
        },
        _xDataCache: null,
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart();
      })
    },
    beforeDestroy() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      getChartImage() {
        this.loading = true;
        this.dataURL = this.chart.getDataURL({
          type: 'png',
          pixelRatio: 2,
        });
        this.$emit('handleSetSetChartImage', this.dataURL);
        this.loading = false;
      },
      replaceValues(array, map) {
        if (!this._xDataCache) {
          this._xDataCache = array.map(item => map[item] || item);
        }
        return this._xDataCache;
      },
      initChart() {
        this.chart = echarts.init(this.$refs.linechart, 'macarons');
        this.setOptions(this.chartData);
      },
      throttleSetOptions: _.throttle(function(summaryData) {
        this.setOptions(summaryData);
      }, 900), // 控制更新频率，单位毫秒

      setOptions(summaryData) {
        if (!this.chart) {
          console.error('Chart instance is not initialized.');
          return;
        }

        let xData = this.replaceValues(Object.keys(summaryData), this.mapping);

        // 使用 requestAnimationFrame 来异步更新图表
        requestAnimationFrame(() => {
          this.chart.setOption({
            title: {
              text: this.text,
              subtext: this.subtext,
              left: 'center'
            },
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
              }
            },
            toolbox: {
              feature: {
                // dataView: {
                //   show: true,
                //   readOnly: false
                // },
                // magicType: {
                //   show: true,
                //   type: ['line', 'bar']
                // },
              }
            },
            xAxis: [{
              type: 'category',
              data: xData,
              axisPointer: {
                type: 'shadow'
              }
            }],
            yAxis: [{
                type: 'value',
                name: '容量',
                axisLabel: {
                  formatter: '{value}'
                }
              },
              {
                type: 'value',
                name: '容量',
                axisLabel: {
                  formatter: '{value}'
                }
              }
            ],
            series: [{
                name: '容量',
                type: 'bar',
                label: {
                  show: true,
                  position: 'outside',
                  formatter: '{b}: {c}' + (this.unitShow == 1 ? 'B' : this.unitShow == 1024 ? 'KB' : this
                      .unitShow == 1024 * 1024 ? 'MB' : this.unitShow == 1024 * 1024 * 1024 ? 'GB' : '个'
                      ) // 显示数值
                },
                tooltip: {
                  valueFormatter: function(value) {
                    return value;
                  }
                },
                data: Object.values(summaryData),
                // itemStyle: {
                //   color: function(params) {
                //     const colors = ['#5793f3', '#d14a61', '#675bba', '#ffa022', '#2f4554', '#91c7ae', '#5aff5a','#72f33a', '#bfd11b', '#1fba8e', '#ffff13', '#094c54', '#b5c79b', '#00aaff'];
                //     return colors[params.dataIndex];
                //   }
                // }
              },
              // {
              //   name: '容量',
              //   type: 'line',
              //   yAxisIndex: 1,
              //   tooltip: {
              //     valueFormatter: function(value) {
              //       return value;
              //     }
              //   },
              //   data: Object.values(summaryData),
              //   itemStyle: {
              //     color: '#ffa022'
              //   }
              // }
            ]
          });
        });
      }
    }
  };
</script>
